import React, {useState} from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import DraggableFlatList from 'react-native-draggable-flatlist';
import {GestureHandlerRootView} from 'react-native-gesture-handler';

export default () => {
  // 测试数据
  const initialData = Array.from({length: 10}, (_, i) => ({
    id: `item-${i}`,
    text: `可拖动项目 ${i + 1}`,
    bgColor: `hsl(${Math.random() * 360}, 70%, 80%)`,
  }));

  const [data, setData] = useState(initialData);

  // 渲染主项目
  const renderItem = ({item, drag, isActive}: any) => {
    console.log('renderItem: ');
    return (
      <TouchableOpacity
        style={[
          styles.item,
          {backgroundColor: isActive ? 'lightgrey' : item.bgColor},
          isActive && styles.activeItem,
        ]}
        onLongPress={drag}
        delayLongPress={200}>
        <Text style={styles.text}>{item.text}</Text>
        <Text style={styles.subText}>长按拖动</Text>
      </TouchableOpacity>
    );
  };

  const handleDragEnd = ({data: newData}: any) => {
    console.log(
      '拖拽结束，新数据顺序:',
      newData.map(i => i.id || i.text || '未知项'),
    );
    setData(newData);
  };

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: 'lightgrey',
      }}>
      <GestureHandlerRootView>
        <DraggableFlatList
          data={data}
          keyExtractor={(item: {id: any}) => item.id}
          renderItem={renderItem}
          onDragEnd={handleDragEnd}
          style={{height: 500, width: '100%', backgroundColor: '#f0f0f0'}}
        />
      </GestureHandlerRootView>
    </View>
  );
};

const styles = StyleSheet.create({
  item: {
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 8,
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 1},
    shadowOpacity: 0.2,
  },
  activeItem: {
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 3},
    shadowOpacity: 0.3,
    shadowRadius: 6,
    elevation: 8,
  },
  text: {
    fontSize: 16,
    fontWeight: '500',
  },
  subText: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
});
